﻿using UnityEngine;
using System;
using System.Collections;

public class TopInfoBar : MonoBehaviour {

    static TopInfoBar instance;

    public static TopInfoBar Instance
    {
        get 
        {
            if (instance == null)
                Create();
            return instance;
        }
        set { instance = value; }
    }

    const string prefabPath = "Prefabs/BottomBar/BottomBar";
    static SCENE[] needBottomMenuScene = new SCENE[10] { SCENE.MainScene, SCENE.SummonMenuScene, SCENE.ShopScene, SCENE.PvPMakeRoomScene, SCENE.PVP_MakeRoomScene21, SCENE.DeckEditScene, 
        SCENE.SelectUnitScene, SCENE.UnitLevelupScene, SCENE.UnitEvolutionScene, SCENE.MainScene};

    UIAnchor m_BottomAnchor;
    public GameObject m_BarRoot;
    public UILabel staminaText;
    public UILabel goldText;
    public UILabel cashText;
	public UILabel staminaNextTickTime;
	public UILabel UserName;
	//public UILabel UserLevel;
	
	//public UISprite charImage;

	public UISprite[] userLevelSprites;

    public GameObject globalMenuObject;
    public Animator sceneAnimator;

    bool m_IsNeedUpdate = false;   //업데이트 관리


    static void Create()
    {
        GameObject prefab = Resources.Load(prefabPath) as GameObject;
        GameObject obj = Instantiate(prefab) as GameObject;
        instance = obj.GetComponent("TopInfoBar") as TopInfoBar;
        DontDestroyOnLoad(obj);
    }

    void Awake()
    {
        m_BottomAnchor = GetComponent<UIAnchor>();
		if( m_BarRoot != null )
        	m_BarRoot.SetActive(false);
    }
	
	// Update is called once per frame
	void Update ()
    {
        if (m_IsNeedUpdate)
        {
            m_IsNeedUpdate = false;
            UpdateIOnFrame();
            UpdateStamina();
        }
	}

    public void SetBarBeforeLevelLoad()  // 씬전환시 콜
    {
        //if( m_BarRoot != null )
        //    m_BarRoot.SetActive(false);
        m_BottomAnchor.uiCamera = null;
        transform.parent = null;
    }

    void SetPos()  // 엑티브 유무 및 포지션 설정
    {
        bool isNeed = false;
        foreach (SCENE scene in needBottomMenuScene)
        {          
            if (CSceneManager.m_Scene == scene)
            {             
                isNeed = true;
                break;
            }
        }

		if( m_BarRoot != null )
        	m_BarRoot.SetActive(isNeed);

        if (isNeed)
        {
            GameObject uiRootCam = GameObject.Find("UI Root (2D)/Camera");
            uiRootCam.camera.cullingMask |= 1 << gameObject.layer;
            uiRootCam.GetComponent<UICamera>().eventReceiverMask |= 1 << gameObject.layer; 

            transform.parent = uiRootCam.transform;
            transform.localScale = Vector3.one;
            transform.localPosition = Vector3.zero;
            transform.parent = null;

            if (uiRootCam != null && m_BottomAnchor != null)
                m_BottomAnchor.uiCamera = uiRootCam.camera;
        }
    }

    void OnLevelWasLoaded() //씬 전환후 동작
    {        
        SetPos();
    }

    public void UpdateInfos()   // 여러번 호출해도 한 프레임에 한번만 업데이트
    {
        m_IsNeedUpdate = true;
    }

    void UpdateIOnFrame()
    {
		if( staminaText != null )
            staminaText.text = MyInfo.Instance.Stamina.ToString();// + " / " + MyInfo.Instance.MaxStamina;

        goldText.text = MyInfo.Instance.Money.ToString();
        cashText.text = MyInfo.Instance.Diamond.ToString();
		UserName.text = MyInfo.Instance.NickName;
		if( MyInfo.Instance.userLevel > 0 )
		{
			if( MyInfo.Instance.userLevel > 9 )
			{
				userLevelSprites[1].spriteName = "No_A" + (MyInfo.Instance.userLevel / 10);
				userLevelSprites[2].spriteName = "No_A" + (MyInfo.Instance.userLevel % 10);
				userLevelSprites[1].gameObject.SetActive(true);
				userLevelSprites[2].gameObject.SetActive(true);
			}
			else if( MyInfo.Instance.userLevel > 99 )
			{
				userLevelSprites[0].spriteName = "No_A" + (MyInfo.Instance.userLevel / 100);
				userLevelSprites[1].spriteName = "No_A" + ((MyInfo.Instance.userLevel % 100) / 10);
				userLevelSprites[2].spriteName = "No_A" + (MyInfo.Instance.userLevel % 10);
				userLevelSprites[0].gameObject.SetActive(true);
				userLevelSprites[1].gameObject.SetActive(true);
				userLevelSprites[2].gameObject.SetActive(true);
			}
			else
			{
				userLevelSprites[2].spriteName = "No_A" + (MyInfo.Instance.userLevel % 10);
				userLevelSprites[2].gameObject.SetActive(true);
			}
		}
		else
		{
			userLevelSprites[2].spriteName = "No_A1";
			userLevelSprites[2].gameObject.SetActive(true);
		}
    }	
	
	void UpdateStamina()
	{
		if( MyInfo.Instance.Stamina < MyInfo.Instance.MaxStamina )
		{
			TimeSpan timeGap = MyInfo.Instance.NextTickTimeForStamina - DateTime.Now;
			if( timeGap.Seconds > 0 )
			{
                //if( staminaNextTickTime != null )
                //{
                //    staminaNextTickTime.gameObject.SetActive(true);
                //    staminaNextTickTime.text = string.Format("{0:00}:{1:00}", (int)timeGap.TotalSeconds/60, (int)timeGap.TotalSeconds%60); 
                //}
			}
			else
			{
				MyInfo.Instance.NextTickTimeForStamina = MyInfo.Instance.NextTickTimeForStamina.AddSeconds(30);
				MyInfo.Instance.AddStamina(10);
				UpdateInfos();
			}
		}
		else
		{
			//staminaNextTickTime.gameObject.SetActive(false);
		}
	}

    void OnClickedGlobalMenuButton()
    {
		if(globalMenuObject.collider.enabled)
		{
			OnHiddenMenuBGButton();
		}
		else 
		{
        	sceneAnimator.Play("Anchor_UI_Main_HiddenMenu_In");
        	globalMenuObject.collider.enabled = true;
		}
    }

    void OnClickAddGoldButton()
    {
        SetBarBeforeLevelLoad();
        OnHiddenMenuBGButton();
        ShopMainManager.currentShopType = SHOPTYPE.GOLD;
        CSceneManager.manager.GoToShopScene();
    }

    void OnClickAddDiamondButton()
    {
        SetBarBeforeLevelLoad();
        OnHiddenMenuBGButton();
        ShopMainManager.currentShopType = SHOPTYPE.CASH;
        CSceneManager.manager.GoToShopScene();
    }

    void OnClickAddStaminaButton()
    {
        SetBarBeforeLevelLoad();
        OnHiddenMenuBGButton();
        ShopMainManager.currentShopType = SHOPTYPE.ITEM;
        CSceneManager.manager.GoToShopScene();
    }


    void OnAchievementButton(GameObject button)
    {        
        RestAPI.singleton.GetMyAchievementList(CallBackOfGetMyAchievementList);
    }

    void CallBackOfGetMyAchievementList(Hashtable returnData)
    {
        RestAPI.singleton.GetMyAchievementValue(CallBackOfGetMyAchievementValue);
    }

    void CallBackOfGetMyAchievementValue(Hashtable returnData)
    {
        OnHiddenMenuBGButton();
        AchievementList.CreateAchievementList();
    }

    void OnColse()  //버튼 누르면 메뉴 닫기
    {
        OnHiddenMenuBGButton();
    }

    // 메뉴 닫는 배경 버튼
    void OnHiddenMenuBGButton()
    {
        sceneAnimator.Play("Anchor_UI_Main_HiddenMenu_Out");
        globalMenuObject.collider.enabled = false;
    }
}
